from fastapi import FastAPI, WebSocket
from apscheduler.schedulers.background import BackgroundScheduler
import requests
import json

app = FastAPI()
clients = []  # 保存 WebSocket 连接

# 模拟股票数据接口
def fetch_stock_data():
    # 替换为真实接口
    response = requests.get("https://api.example.com/stock_data")
    return response.json()

# 条件筛选函数
def filter_stocks(data):
    selected = []
    for stock in data:
        # 条件示例：涨幅 > 5%，成交量 > 1000 万
        if stock['change_percent'] > 5 and stock['volume'] > 10000000:
            selected.append(stock)
    return selected

# 定时任务：实时监控
def monitor_stocks():
    data = fetch_stock_data()
    selected_stocks = filter_stocks(data)
    
    if selected_stocks:
        # 通知前端
        for client in clients:
            try:
                client.send_text(json.dumps(selected_stocks))
            except:
                clients.remove(client)

        # 发送通知到 Gotify
        notify(selected_stocks)

# Gotify 通知
def notify(stocks):
    for stock in stocks:
        message = f"{stock['name']} ({stock['symbol']}) 符合条件！当前涨幅：{stock['change_percent']}%"
        requests.post("http://minio.tianjunli.top:666/message", json={
            "title": "选股提醒",
            "message": message,
            "priority": 5
        })

# 启动定时任务
scheduler = BackgroundScheduler()
scheduler.add_job(monitor_stocks, 'interval', seconds=60)  # 每 60 秒检查一次
scheduler.start()

# WebSocket 连接
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    clients.append(websocket)
    try:
        while True:
            await websocket.receive_text()  # 保持连接
    except:
        clients.remove(websocket)
